<template>
  <div v-if="visible" class="modal-overlay" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ isEdit ? $t('account.editAccount') : $t('account.addAccount') }}</h3>
        <button @click="closeModal" class="close-btn">&times;</button>
      </div>

      <form @submit.prevent="handleSubmit" class="account-form">
        <div class="form-group">
          <label>{{ $t('account.title') }} *</label>
          <input
            v-model="form.title"
            type="text"
            :placeholder="$t('account.titlePlaceholder')"
            required
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label>{{ $t('account.website') }}</label>
          <input
            v-model="form.website"
            type="url"
            placeholder="https://example.com"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label>{{ $t('account.username') }} *</label>
          <input
            v-model="form.username"
            type="text"
            :placeholder="$t('account.usernamePlaceholder')"
            required
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label>{{ $t('account.password') }} *</label>
          <div class="password-input-wrapper">
            <div class="password-input">
              <input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                :placeholder="$t('account.passwordPlaceholder')"
                required
                class="form-input"
              />
              <button
                type="button"
                @click="togglePassword"
                class="password-toggle"
              >
                {{ showPassword ? '🙈' : '👁️' }}
              </button>
            </div>
            <button
              type="button"
              @click="showPasswordGenerator = true"
              class="password-generate-btn"
              :title="$t('account.usePasswordGenerator')"
            >
              🔑 {{ $t('account.generate') }}
            </button>
          </div>
          <PasswordStrengthMeter
            v-if="form.password"
            :password="form.password"
            :show-score="true"
            :show-details="false"
          />
        </div>

        <div class="form-group">
          <label>{{ $t('account.category') }}</label>
          <select v-model="form.category_id" class="form-select">
            <option value="">{{ $t('account.selectCategory') }}</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label>{{ $t('account.encryptMethod') }}</label>
          <select v-model="form.encrypt_method" class="form-select">
            <option value="AES-256-GCM">AES-256-GCM ({{ $t('common.info') }})</option>
            <option value="AES-256-CBC">AES-256-CBC</option>
            <option value="AES-128-GCM">AES-128-GCM</option>
            <option value="AES-128-CBC">AES-128-CBC</option>
            <option value="SM4">SM4</option>
          </select>
          <small class="form-hint">{{ $t('account.encryptMethodHint') }}</small>
        </div>

        <div class="form-group">
          <label>{{ $t('account.notes') }}</label>
          <textarea
            v-model="form.notes"
            :placeholder="$t('account.notesPlaceholder')"
            class="form-textarea"
            rows="3"
          ></textarea>
        </div>

        <div class="form-actions">
          <button type="button" @click="closeModal" class="btn-cancel">
            {{ $t('common.cancel') }}
          </button>
          <button type="submit" :disabled="isSubmitting" class="btn-submit">
            {{ isSubmitting ? (isEdit ? $t('account.updating') : $t('account.saving')) : (isEdit ? $t('common.edit') : $t('common.save')) }}
          </button>
        </div>
      </form>
    </div>

    <!-- 密码生成器 -->
    <PasswordGeneratorModal
      :visible="showPasswordGenerator"
      @close="showPasswordGenerator = false"
      @apply="applyGeneratedPassword"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import PasswordStrengthMeter from './PasswordStrengthMeter.vue'
import PasswordGeneratorModal from './PasswordGeneratorModal.vue'

const { t: $t } = useI18n()

interface Account {
  id?: number
  title: string
  website: string
  username: string
  password: string
  category_id: number | string
  notes: string
  encrypt_method?: string
}

interface Category {
  id: number
  name: string
}

const props = defineProps<{
  visible: boolean
  isEdit: boolean
  account?: Account
  categories: Category[]
}>()

const emit = defineEmits<{
  close: []
  save: [account: Account]
}>()

// 响应式数据
const showPassword = ref(false)
const isSubmitting = ref(false)
const showPasswordGenerator = ref(false)

const form = ref<Account>({
  title: '',
  website: '',
  username: '',
  password: '',
  category_id: '',
  notes: '',
  encrypt_method: 'AES-256-GCM'
})

// 应用生成的密码
const applyGeneratedPassword = (password: string) => {
  form.value.password = password
  showPassword.value = true
}

// 监听账号数据变化，用于编辑模式
watch(() => props.account, (newAccount) => {
  if (newAccount && props.isEdit) {
    console.log('编辑账号数据:', newAccount)
    form.value = {
      ...newAccount,
      // 确保加密方式有默认值，如果账号没有指定加密方式，使用默认值
      encrypt_method: newAccount.encrypt_method || 'AES-256-GCM'
    }
    console.log('表单数据:', form.value)
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (visible && !props.isEdit) {
    // 新增模式，清空表单
    form.value = {
      title: '',
      website: '',
      username: '',
      password: '',
      category_id: '',
      notes: '',
      encrypt_method: 'AES-256-GCM'
    }
  }
})

// 方法
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const closeModal = () => {
  emit('close')
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    // 基本验证
    if (!form.value.title.trim() || !form.value.username.trim() || !form.value.password.trim()) {
      alert($t('validation.requiredFields'))
      return
    }

    emit('save', { ...form.value })
  } catch (error) {
    console.error('提交表单失败:', error)
    alert($t('message.saveFailed'))
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #666;
}

.account-form {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.password-input-wrapper {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.password-input {
  position: relative;
  flex: 1;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
}

.password-toggle:hover {
  color: #333;
}

.password-generate-btn {
  padding: 8px 12px;
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  white-space: nowrap;
  transition: all 0.2s;
}

.password-generate-btn:hover {
  background: #73d13d;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
}

.form-textarea {
  resize: vertical;
  min-height: 60px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.btn-cancel {
  padding: 8px 16px;
  background: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel:hover {
  background: #e6e6e6;
}

.btn-submit {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.btn-submit:hover:not(:disabled) {
  background: #40a9ff;
}

.btn-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.form-hint {
  display: block;
  margin-top: 4px;
  color: #666;
  font-size: 12px;
}
</style>